/**
 * 
 */
package info.niwota.search;

import java.io.IOException;
import java.security.Key;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author qiangli
 * 
 */
@SuppressWarnings("serial")
public class BrowseServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(BrowseServlet.class
			.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Key key = (Key) req.getSession().getAttribute(Constants.HTML_KEY);

		final String uri = req.getRequestURI();
		
		try {
			int idx = uri.indexOf("/", 1);
			if (idx == -1) {
				//missing url
				resp.sendRedirect("/search");
				return;
			}
			
			// /browse, /view, /assets
			//String dec = CryptUtils.decrypt(key, uri.substring(idx + 1));
			String[] sa = HtmlScrambler.decrypt(key, uri.substring(idx + 1));
			String url = sa[0];
			final int cook = parseInt(sa[1], 1);
			final String[] terms = sa[2].split("\t");
			
			log.info("uri: " + uri + " decrypted: " + url);
			
			boolean b = Boolean.parseBoolean(req.getParameter("original"));
			
			if (b) {
				resp.sendRedirect(url);
			} else {
				HttpClient.fetch(url, terms, cook, req, resp);
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	private int parseInt(String s, int def) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return def;
	}
}
